<template>
    <el-card class="box-card"  style="border-right: none; border-bottom: none !important; border-top: none !important;border-radius: 0;">
      <div class="card-header">
        <span>任务分类管理</span>
        <el-button type="primary" @click="AddTaskCategory">新增</el-button>
      </div>
      <el-form :inline="true" :model="formInline" class="form-inline">
      <el-form-item label="分类名称">
        <el-input v-model="formInline.name" placeholder="分类名称" clearable />
      </el-form-item>
      <el-form-item label="状态">
        <el-select
          v-model="formInline.state"
          placeholder="全部"
          clearable
        >
          <el-option label="全部" value="" />
          <el-option label="启用" value="1" />
          <el-option label="禁用" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">搜索</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
  </el-form>
  
  <el-table :data="list" height="580px" style="width: 100%" v-loading="loading">
    <!-- 渲染用户名 -->
    <el-table-column prop="name" label="分类名称" min-width="150" />
    <!-- 渲染状态 -->
    <el-table-column label="状态" min-width="100">
      <template #default="scope">
        <el-tag v-if="scope.row.status === 1" type="success">{{scope.row.status_text}}</el-tag>
        <el-tag v-else type="danger">{{scope.row.status_text}}</el-tag>
      </template>
    </el-table-column>

    <el-table-column prop="sort" label="排序" min-width="150" />

    <!-- 渲染创建时间 -->
    <el-table-column prop="created_at" label="创建时间" width="160" />

    <!-- 渲染更新时间 -->
    <el-table-column prop="updated_at" label="更新时间" width="160" />

    <!-- 操作 -->
    <el-table-column fixed="right" label="操作" width="200" >
      <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
        <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <el-pagination class="el-p"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :small="small"
      :disabled="disabled"
      :background="background"
      layout="total, sizes, prev, pager, next"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </el-card>

  <el-dialog
    v-model="dialogVisible"
    :title="dialogType === 'add' ? '新增任务类' : '编辑任务类'"
    width="500px"
    :close-on-click-modal="false"
  >
    <AddTaskCategoryForm ref="addFormRef" :form-data="currentFormData" :is-edit="dialogType === 'edit'" />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref,reactive,watch } from 'vue';
import { taskCategoryService } from '@/api/taskCategoryService';
import { ElMessage, ElMessageBox } from 'element-plus';
import AddTaskCategoryForm from '@/components/AddTaskCategoryForm.vue';
const addFormRef = ref(null);
const formRef = ref(null);
const formInline = reactive({
    name: '',
    state: ''
  });
const dialogVisible = ref(false);
const list = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const dialogType = ref('add');
const currentFormData = ref({});
const small = ref(false);
const isEdit = ref(false);
const loading = ref(false);
const formData = ref({
    name: '',
    state: ''
  });
const handleEdit = (index, row) => {
    dialogVisible.value = true;
    dialogType.value = 'edit';
    currentFormData.value = row;
    isEdit.value = true;
    formData.value = { ...row };
  };
const handleDelete = (row) => {
    ElMessageBox.confirm('是否删除该分类?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
        taskCategoryService.del(row.id).then((res) => {
          ElMessage.success('删除成功!');
          getList();
        });
    });
  };
const getList = async() => {
    loading.value = true;
    try{
        const params = {
            name: formInline.name,
            status: formInline.state,
            page: currentPage.value,
            pageSize: pageSize.value
          };
        const res = await taskCategoryService.getList(params);
        list.value = res.data;
        total.value = res.total;
    }catch (error) {
        ElMessage.error('获取数据失败!');
    } finally {
        loading.value = false; // 无论成功还是失败都停止加载状态
    }
  };
const resetForm = () => {
    formInline.name = '';
    formInline.state = '';
    getList();
  };
const onSubmit = () => {
    getList();
};
const handleSizeChange = (val) => {
    pageSize.value = val;
    getList();
  };
const handleCurrentChange = (val) => {
    currentPage.value = val;
    getList();
  };
const resetDialog = () => {
    dialogType.value = 'add';
    currentFormData.value = null;
    if (addFormRef.value) {
      addFormRef.value.resetForm();
    }
};
watch(dialogVisible, (newVal) => {
    if (!newVal) {
      resetDialog();
    }
});

getList();

const submitForm = async () => {
    // 检查表单引用是否存在
    if (!addFormRef.value) return;
    
    // 验证表单数据合法性
    const isValid = await addFormRef.value.validateForm();
    // 如果表单数据不合法，则终止操作
    if (!isValid) return;
    
    try {
      // 复制表单数据
      const formData = { ...addFormRef.value.form };
      
      // 根据dialogType的值决定是添加还是更新管理员信息
      if (dialogType.value === 'add') {
        formData.id = null; // 确保添加时没有ID
        // 添加
        await taskCategoryService.add(formData);
        ElMessage.success('新增成功');
      } else {
        // 更新
        await taskCategoryService.update(formData.id,formData);
        ElMessage.success('更新成功');
      }
      
      // 关闭对话框
      dialogVisible.value = false;
      // 刷新用户列表
      getList();
    } catch (error) {
      // 处理添加或更新操作失败的情况
      //ElMessage.error(dialogType.value === 'add' ? '新增管理员失败' : '更新管理员失败');
    }
};
const AddTaskCategory = () => {
    // dialogVisible.value = true;
    // dialogType.value = 'add';
    // currentFormData.value = {};
    // isEdit.value = false;
    // formData.value = {};
    dialogType.value = 'add';
    currentFormData.value = null;
    if (addFormRef.value) {
      addFormRef.value.resetForm();
    }
    dialogVisible.value = true;
    isEdit.value = false;
};
</script>
<style scoped>
  .form-inline {
    margin: 20px 0;
    border-bottom: 1px solid #e4e7ed;
  }
  .el-p{
    margin-top: 15px;
    display: flex;
    justify-self: flex-end;
  }
  .el-select{
    width: 85px;
  }
  .card-header{
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 50px;
    border-bottom: 1px solid #e4e7ed;
    
  }
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
  .el-descriptions {
    margin: 20px;
  }
</style>